package com.wangsb.util.converter;

import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @Description: TODO
 * @author: shenbing.wang@hand-china
 * @date: 2021年02月21日 11:07
 */
public class MyDateConverterUtil implements Converter<String, Date> {
    @SneakyThrows
    @Override
    public Date convert(String source) {
        if (!StringUtils.isEmpty(source)) {
            String pattern = "\\d{4}(\\-|\\/|.)\\d{1,2}\\1\\d{1,2}";
            //  应收日期 2019/1/1
            // 2019-01-02
            // 2019.02.02
            // 20190909
            if (Pattern.matches(pattern, source)) {
                DateFormat df = new SimpleDateFormat(source);
                return df.parse(source);
            }
        }
        return null;
    }


    public static void main(String[] args) {

        String pattern ="\\d{4}(\\-|\\/|.)\\d{1,2}\\1\\d{1,2}";
        //  应收日期 2019/1/1
        // 2019-01-02
        // 2019.02.02
        // 20190909

        boolean isMatchDate1 = Pattern.matches(pattern, "2019-01-02");
        boolean isMatchDate2 = Pattern.matches(pattern, "2019/1/1");
        boolean isMatchDate3 = Pattern.matches(pattern, "2019.02.02");
        boolean isMatchDate4 = Pattern.matches(pattern, "20190909");
        System.out.println("字符串中是否是日期' 子字符串? " + isMatchDate1+";"+isMatchDate2+";"+isMatchDate3+";"+isMatchDate4+";");


    }
}
